<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">Holyzq 后台登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登 录</el-button>

      <div style="position:relative">
        <div class="tips">
          <span>Username : admin</span>
          <span>Password : any</span>
        </div>
        <div class="tips">
          <span style="margin-right:18px;">Username : editor</span>
          <span>Password : any</span>
        </div>

<!--        <el-button class="thirdparty-button" type="primary" @click="RegisterDialog = true">-->
<!--          没有账号？去注册-->
<!--        </el-button>-->
      </div>
    </el-form>

    <!--注册管理员账号-->
    <el-dialog title="注册管理员账号" :visible.sync="RegisterDialog" center>
      <el-card>
        <el-form ref="ruleForm" :model="ruleForm" label-width="90px">
          <el-form-item label="用户名" class="register-input">
            <el-input v-model="ruleForm.username" type="text" />
          </el-form-item>
          <el-form-item label="上传头像">
            <el-upload
              class="avatar-uploader"
              :data="qiniuForm"
              :before-upload="beforeUpload"
              :on-success="uploadSuccess"
              action="https://upload.qiniup.com"
            >
              <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="ruleForm.password" type="password" />
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input v-model="ruleForm.checkPassword" type="password" />
          </el-form-item>

          <el-form-item style="margin-left: 408px;background-color: #ffffff">
            <el-button size="medium" @click="resetForm('ruleForm')">重置</el-button>
            <el-button type="primary" size="medium" @click="submitForm('ruleForm')">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import { setStorage } from '@/utils/auth'
import { login, register } from '@/api/user'
import { v4 as uuidv4 } from 'uuid'
import { fetchUpload } from '@/api/upload'
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      qiniuForm: {
        key: '', // 文件名称
        token: ''
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      RegisterDialog: false,
      ruleForm: {
        username: '',
        password: '',
        checkPassword: '',
        avatar: ''
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          login(this.loginForm).then((res) => {
            if (res.code === 20000) {
              setStorage('token', res.data.token)
              setStorage('user', JSON.stringify(res.data.user))
              this.loading = false
              this.$message.success(res.message)
              this.$router.push({ path: '/' })
              window.location.reload()
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 上传之前
    async beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像只能是 JPG或PNG 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传头像大小不能超过 2MB!')
      }

      // 如果验证失败，返回假
      if (isJPG && isLt2M === false) return false

      // 如果验证成功，获取token
      const fileType = file.type === 'image/jpeg' ? 'jpg' : 'png' // 获取扩展名
      const res = await fetchUpload()
      this.qiniuForm = {
        key: `${uuidv4()}.${fileType}`, // 文件名称
        token: res.data.uploadToken
      }
      return true
    },
    // 上传成功，获取图片地址
    uploadSuccess(res) {
      this.ruleForm.avatar = 'https://image.holyzq.com/' + res.key
    },
    // 管理员注册
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return
        register(this.ruleForm).then((res) => {
          if (res.code !== 20000) return this.$message.error(res.message)
          this.$message.success(res.message)
          this.ruleForm.username = ''
          this.ruleForm.password = ''
          this.ruleForm.checkPassword = ''
          this.ruleForm.avatar = ''
          this.RegisterDialog = false
        })
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
  .tips {
    font-size: 14px;
    color: #2d3a4b;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    padding-top: 15px;
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
